<?php include "classes.inc" ?>
<?php include "constants.inc" ?>
<?php session_start(); ?>
<?php
    $title = trim($_POST['newsTitle']);
    $intro = trim($_POST['newsIntro']);
    $introImage = trim($_POST['newsIntroImage']);
    $content = trim($_POST['newsContent']);
    if ( !empty($title) && !empty($intro) && !empty($content) ) {
        $user = $_SESSION['user'];

        $connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
        mysql_select_db(DB_CATALOG);
        $result = mysql_query("SET AUTOCOMMIT=0", $connect);
        $result = mysql_query("BEGIN", $connect);

        $query = sprintf("INSERT INTO news_item (title, intro, introImage, message) VALUES ('%s', '%s', '%s', '%s')",
            mysql_real_escape_string(utf8_decode($title)),
            mysql_real_escape_string(utf8_decode($intro)),
            mysql_real_escape_string($introImage),
            mysql_real_escape_string(utf8_decode($content)));

        if ($result = mysql_query($query, $connect)) {
            $query = "SELECT LAST_INSERT_ID() AS news_id";
            $result = mysql_query($query, $connect);
            $row = mysql_fetch_assoc($result);
            $query = sprintf("INSERT INTO news_history (user_id, news_id) VALUES ('%d', '%d')", $user->user_id, $row['news_id']);
            if ($result != mysql_query($query, $connect)) {
                $result = mysql_query("ROLLBACK", $connect);
                echo "Nieuwshistoriek kon niet worden opgeslagen: ".mysql_error();
            }
        } else {
            echo "Nieuwsbericht kon niet worden opgeslagen: ".mysql_error();
        }

        $result = mysql_query("COMMIT", $connect);
        
    } else {
        echo "Titel, intro en tekst zijn verplichte velden.";
    }
?>
